import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '超全文本演示',
      theme: ThemeData(
        fontFamily: 'Roboto',
        textTheme: GoogleFonts.latoTextTheme(),
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  int _counter = 0;
  bool _isHighlight = false;
  double _textScale = 1.0;
  late AnimationController _animationController;
  late AnimationController _countController;
  late Animation<int> _countAnimation;
  int _displayedCount = 0;
  bool _showCopied = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(reverse: true);

    _countController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 600),
    );
    _countAnimation = IntTween(
      begin: 0,
      end: _counter,
    ).animate(_countController)..addListener(() {
      setState(() {
        _displayedCount = _countAnimation.value;
      });
    });
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
      _animateCount();
    });
  }

  void _decrementCounter() {
    setState(() {
      _counter--;
      _animateCount();
    });
  }

  void _resetCounter() {
    setState(() {
      _counter = 0;
      _animateCount();
    });
  }

  void _toggleHighlight() => setState(() => _isHighlight = !_isHighlight);
  void _updateScale(double value) => setState(() => _textScale = value);

  void _animateCount() {
    _countAnimation = IntTween(
      begin: _displayedCount,
      end: _counter,
    ).animate(_countController);
    _countController.forward(from: 0);
  }

  @override
  void dispose() {
    _animationController.dispose();
    _countController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Text演示'),
        actions: [
          IconButton(
            icon: const Icon(Icons.highlight),
            onPressed: _toggleHighlight,
          ),
          IconButton(
            icon: const Icon(Icons.format_size),
            onPressed:
                () => showDialog(
                  context: context,
                  builder:
                      (_) => AlertDialog(
                        title: const Text('调整文字缩放'),
                        content: Slider(
                          value: _textScale,
                          min: 0.5,
                          max: 3.0,
                          onChanged: _updateScale,
                        ),
                      ),
                ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: MediaQuery(
          data: MediaQuery.of(context).copyWith(textScaleFactor: _textScale),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildSectionTitle('🔢 动画计数器'),
              Row(
                children: [
                  ElevatedButton(
                    onPressed: _incrementCounter,
                    child: const Text('增加'),
                  ),
                  const SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: _decrementCounter,
                    child: const Text('减少'),
                  ),
                  const SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: _resetCounter,
                    child: const Text('重置'),
                  ),
                  const SizedBox(width: 20),
                  AnimatedSwitcher(
                    duration: const Duration(milliseconds: 400),
                    child: Text(
                      '$_displayedCount',
                      key: ValueKey(_displayedCount),
                      style: GoogleFonts.robotoMono(
                        fontSize: 32,
                        color: Colors.deepPurple,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 40),

              _buildSectionTitle('🌈 动态文字效果'),

              // 动画渐变颜色
              AnimatedBuilder(
                animation: _animationController,
                builder: (_, child) {
                  final value = _animationController.value;
                  return Text(
                    '动态渐变文字',
                    style: TextStyle(
                      fontSize: 24,
                      foreground:
                          Paint()
                            ..shader = LinearGradient(
                              colors: [
                                Colors.blue,
                                Color.lerp(Colors.blue, Colors.purple, value)!,
                              ],
                            ).createShader(Rect.fromLTWH(0, 0, 200, 20)),
                    ),
                  );
                },
              ),
              const SizedBox(height: 20),

              // 3D立体文字
              Stack(
                children: [
                  Text(
                    '3D效果',
                    style: GoogleFonts.anton(
                      fontSize: 40,
                      foreground:
                          Paint()
                            ..style = PaintingStyle.stroke
                            ..color = Colors.grey
                            ..strokeWidth = 2,
                    ),
                  ),
                  Text(
                    '3D效果',
                    style: GoogleFonts.anton(
                      fontSize: 40,
                      color: Colors.blue[400],
                      shadows: [
                        Shadow(
                          color: Colors.black.withOpacity(0.2),
                          offset: const Offset(4, 4),
                          blurRadius: 4,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),

              // 文字路径效果
              CustomPaint(
                size: const Size(200, 100),
                painter: _TextPathPainter(),
              ),
              const SizedBox(height: 40),

              _buildSectionTitle('📚 复杂排版示例'),

              // 多列文字布局
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Text(
                      '左栏文本：${'Flutter是Google开源的UI工具包，用于构建跨平台应用。' * 5}',
                      textAlign: TextAlign.justify,
                    ),
                  ),
                  const VerticalDivider(width: 20),
                  Expanded(
                    child: Text(
                      '右栏文本：${'Dart语言提供了强大的异步编程支持。' * 8}',
                      textAlign: TextAlign.end,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),

              // 文字环绕图片
              Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                children: [
                  SizedBox(width: 100, child: Placeholder(fallbackHeight: 80)),
                  const SizedBox(width: 10),
                  Text('${'文字环绕效果演示，此处应显示图片被文本环绕的效果。' * 6}'),
                ],
              ),
              const SizedBox(height: 40),

              _buildSectionTitle('🌍 多语言支持'),

              // 复杂多语言混排
              const Text.rich(
                TextSpan(
                  children: [
                    TextSpan(text: '中文 '),
                    TextSpan(
                      text: 'العربية',
                      style: TextStyle(
                        fontFamily: 'NotoNaskhArabic',
                        fontSize: 18,
                      ),
                    ),
                    TextSpan(text: ' English '),
                    TextSpan(
                      text: '日本語',
                      style: TextStyle(fontFamily: 'NotoSansJP', fontSize: 18),
                    ),
                    TextSpan(text: ' हिन्दी'),
                  ],
                ),
              ),
              const SizedBox(height: 20),

              _buildSectionTitle('🎨 高级装饰效果'),

              // 渐变下划线
              ShaderMask(
                shaderCallback:
                    (bounds) => LinearGradient(
                      colors: [Colors.red, Colors.blue],
                    ).createShader(bounds),
                child: const Text(
                  '渐变下划线示例',
                  style: TextStyle(
                    fontSize: 24,
                    decoration: TextDecoration.underline,
                    decorationThickness: 3,
                  ),
                ),
              ),
              const SizedBox(height: 20),

              // 文字背景框
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  gradient: LinearGradient(
                    colors: [Colors.blue[100]!, Colors.purple[100]!],
                  ),
                ),
                child: const Text('带背景框的文本', style: TextStyle(fontSize: 20)),
              ),
              const SizedBox(height: 20),

              // 文字倒影效果
              Stack(
                children: [
                  const Text(
                    '倒影文字',
                    style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
                  ),
                  Transform(
                    transform: Matrix4.rotationX(3.14),
                    alignment: Alignment.center,
                    child: Opacity(
                      opacity: 0.3,
                      child: Text(
                        '倒影文字',
                        style: TextStyle(
                          fontSize: 32,
                          fontWeight: FontWeight.bold,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 40),

              _buildSectionTitle('🖱️ 交互式文本'),

              // 可拖拽文字
              Draggable<String>(
                data: 'Flutter',
                feedback: Material(
                  child: Text(
                    'Flutter',
                    style: TextStyle(
                      fontSize: 24,
                      color: Colors.blue.withOpacity(0.7),
                    ),
                  ),
                ),
                child: const Text(
                  '拖拽我 (Flutter)',
                  style: TextStyle(fontSize: 24),
                ),
              ),
              const SizedBox(height: 20),

              // 文字悬停效果
              MouseRegion(
                cursor: SystemMouseCursors.click,
                child: GestureDetector(
                  onTap:
                      () => ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('你点击了悬停效果文字')),
                      ),
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: _isHighlight ? Colors.amber[100] : null,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: const Text('悬停效果文字'),
                  ),
                ),
              ),
              const SizedBox(height: 40),

              _buildSectionTitle('🔗 富文本超链接与可复制'),

              // 富文本超链接
              RichText(
                text: TextSpan(
                  text: '访问 ',
                  style: TextStyle(color: Colors.black, fontSize: 18),
                  children: [
                    WidgetSpan(
                      child: GestureDetector(
                        onTap: () async {
                          final url = 'https://www.bilibili.com/ ';
                          if (await canLaunchUrl(Uri.parse(url))) {
                            await launchUrl(Uri.parse(url));
                          } else {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(content: Text('无法打开链接')),
                            );
                          }
                        },
                        child: Text(
                          'B站官网',
                          style: TextStyle(
                            color: Colors.blue,
                            decoration: TextDecoration.underline,
                          ),
                        ),
                      ),
                    ),
                    const TextSpan(text: ' 获取更多信息。'),
                  ],
                ),
              ),

              // 可复制文本
              Row(
                children: [
                  Expanded(
                    child: SelectableText(
                      '这是一段可复制的文本，长按或双击可复制。',
                      style: const TextStyle(fontSize: 18),
                      onSelectionChanged: (selection, cause) {},
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.copy),
                    onPressed: () async {
                      await Clipboard.setData(
                        const ClipboardData(text: '这是一段可复制的文本，长按或双击可复制。'),
                      );
                      setState(() {
                        _showCopied = true;
                      });
                      Future.delayed(const Duration(seconds: 1), () {
                        setState(() {
                          _showCopied = false;
                        });
                      });
                    },
                  ),
                  if (_showCopied)
                    const Text('已复制!', style: TextStyle(color: Colors.green)),
                ],
              ),
              const SizedBox(height: 40),

              _buildSectionTitle('🖋️ 自定义字体与阴影'),

              // 自定义字体
              Text(
                'Poppins字体演示',
                style: GoogleFonts.poppins(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                  color: Colors.deepOrange,
                ),
              ),
              const SizedBox(height: 10),

              // 阴影效果
              Text(
                '带阴影的文字',
                style: TextStyle(
                  fontSize: 28,
                  color: Colors.indigo,
                  shadows: [
                    Shadow(
                      color: Colors.black.withOpacity(0.3),
                      offset: const Offset(3, 3),
                      blurRadius: 6,
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 10),

              // 描边效果
              Stack(
                children: [
                  Text(
                    '描边文字',
                    style: TextStyle(
                      fontSize: 32,
                      foreground:
                          Paint()
                            ..style = PaintingStyle.stroke
                            ..strokeWidth = 2
                            ..color = Colors.black,
                    ),
                  ),
                  const Text(
                    '描边文字',
                    style: TextStyle(fontSize: 32, color: Colors.white),
                  ),
                ],
              ),
              const SizedBox(height: 40),

              _buildSectionTitle('😃 Emoji与图标混排'),

              // Emoji与图标混排
              RichText(
                text: TextSpan(
                  style: const TextStyle(fontSize: 24),
                  children: [
                    const TextSpan(text: 'Flutter '),
                    WidgetSpan(
                      alignment: PlaceholderAlignment.middle,
                      child: Icon(
                        Icons.flutter_dash,
                        color: Colors.blue,
                        size: 28,
                      ),
                    ),
                    const TextSpan(text: ' 是 '),
                    const TextSpan(text: '🚀', style: TextStyle(fontSize: 28)),
                    const TextSpan(text: ' 的UI工具包！'),
                  ],
                ),
              ),
              const SizedBox(height: 40),

              _buildSectionTitle('🔤 字体变体'),

              // 小型大写字母
              const Text(
                'Small Caps Demo',
                style: TextStyle(fontFeatures: [FontFeature.enable('smcp')]),
              ),
              const SizedBox(height: 10),

              // 旧式数字
              const Text(
                '12345',
                style: TextStyle(fontFeatures: [FontFeature.oldstyleFigures()]),
              ),
              const SizedBox(height: 10),

              // 连字效果
              Text(
                'fi fl ff',
                style: GoogleFonts.lato(
                  textStyle: const TextStyle(
                    fontSize: 24,
                    fontFeatures: [FontFeature.enable('liga')],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 15),
      padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
      decoration: BoxDecoration(
        color: Colors.blue[50],
        borderRadius: BorderRadius.circular(5),
      ),
      child: Text(
        title,
        style: GoogleFonts.poppins(
          fontSize: 18,
          fontWeight: FontWeight.w600,
          color: Colors.blue[900],
        ),
      ),
    );
  }
}

class _TextPathPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint =
        Paint()
          ..color = Colors.blue
          ..style = PaintingStyle.stroke
          ..strokeWidth = 2;

    final path =
        Path()
          ..moveTo(0, size.height / 2)
          ..quadraticBezierTo(
            size.width / 4,
            size.height,
            size.width / 2,
            size.height / 2,
          )
          ..quadraticBezierTo(
            size.width * 3 / 4,
            0,
            size.width,
            size.height / 2,
          );

    canvas.drawPath(path, paint);

    final textPainter = TextPainter(
      text: const TextSpan(
        text: 'Path Text',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20,
          fontWeight: FontWeight.bold,
        ),
      ),
      textDirection: TextDirection.ltr,
    )..layout();

    textPainter.paint(canvas, Offset.zero);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
